package datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import jdbctest.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/14.
 */
public class UserDao {
    private ComboPooledDataSource cpsd = C3POUtils.getDataSource();

    public Connection getConnection(){
        Connection conn = null;
        try {
            conn = cpsd.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public List<User> findPage(int pageNum, int pageSize){
        String sql = "select * from user where id <= ? and id > ?";
        List<User> userList = null;
        try {
            PreparedStatement preparedStatement = this.getConnection().prepareStatement(sql);
            preparedStatement.setInt(1, pageNum * pageSize);
            preparedStatement.setInt(2, pageNum * pageSize - pageSize);

            ResultSet resultSet = preparedStatement.executeQuery();
            userList = new ArrayList<User>();
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));//获得第一列的值
                //int id rs.getInt("id");// 获得id列的值
                user.setName(resultSet.getString(2));//获得第二列的值
                user.setAge(resultSet.getInt(3));//获得第三列的值

                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userList;
    }

}
